/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2016-08-22 14:56:58
 * @version $Id$
 */


var $$ = function(id) {
    return document.getElementById(id);
};

function log(content, title) {
    var args = Array.prototype.slice.call(arguments);
    if (!title) {
        title = '';
    } else {
        args.unshift(title + ' -- ');
        args.pop();
    }
    args.unshift('[app]:');
    console.log.apply(console, args);
}

//jsonp
function Jsonp($http) {
    this.get = function(url, callback) {
        $http.jsonp(url).success(function(data) {
            callback(data);
        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            log('请检查网络连接')
        });
    }
}

function getQueryString(thisUrl, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    //var r = window.location.search.substr(1).match(reg);
    var r1 = thisUrl.toString().split("?")[1];
    if (r1 != null) {
        var r = r1.match(reg);
        if (r != null) return unescape(r[2]);
    }
    return null;
}

//弹出层控制器
function Popup(scope, data) {
    this.open = function() {
        scope[data].show = true;
    }
    this.close = function() {
        scope[data].show = false;
        console.log('close')
    }
    this.delay = function(time, callback) {
        if (callback == undefined) {
            callback = function() {}
        }
        scope[data].show = true;
        setTimeout(function() {
            console.log('timeout')
            scope[data].show = false;
            scope.$digest();
            callback();
        }, time);
    }
}

//操作控制面板
function Ctrlbtn() {

    this.lock_btn = function(id) {
        $$(id).setAttribute('disabled', 'disabled');
    };
    this.unlock_btn = function(id) {
        $$(id).removeAttribute('disabled');
    };
    this.lock = function(array) {
        for (var i = array.length - 1; i >= 0; i--) {
            $$(array[i]).setAttribute('disabled', 'disabled');
        }
    };
    this.unlock = function(array) {
        for (var i = array.length - 1; i >= 0; i--) {
            $$(array[i]).removeAttribute('disabled');
        }
    };
};

/**
 * 随机数生成
 * @param  {[type]} n [description]
 * @return {[type]}   [description]
 */
function generateMixed(n) {
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var res = "";
    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}
/**
 * XHR
 * @return {[type]} [description]
 */
function createXHR() {
    if (window.XMLHttpRequest) {
        // 新浏览器
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        // IE5,IE6
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

function xhrthen(xhr, callback) {
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                console.log(xhr.responseText)
                callback();
            } else {
                console.log(xhr.status)
                console.log(xhr.responseText)
                callback();
            }
        }
    };
};

/**
 * imarker
 * @param {[type]} mapObj [description]
 */
function Imarker(mapObj, $http, md, infowindow) {
    Ctrlbtn.call(this);

    var lock_btn = this.lock_btn;
    var unlock_btn = this.unlock_btn;
    var unlock = this.unlock;
    var lock = this.lock;

    var markers = [],
        marker = undefined,
        listers = [],
        isEdit = false,
        lng = undefined,
        lat = undefined;

    this.set_pos = function(mlng, mlat) {
        lng = mlng;
        lat = mlat;
    }
    this.get_pos = function() {
        return {
            lng: lng,
            lat: lat
        }
    }
    this.set_isEdit = function(bool) {
        isEdit = bool;
    }
    this.get_isEdit = function() {
        return isEdit;
    }
    this.get_marker = function() {
        return marker;
    }

    this.add = function(lng, lat, callback) {
        if (lng && lat) {
            var marker = new AMap.Marker({
                position: [lng, lat],
                map: mapObj,
                extData: null
            });
            markers.push(marker);
            //新marker绑定必须事件
            ev_bind(markers.length - 1);
        } else {
            alert("请耐心等待地址查询结果")
        }
        callback();
    };

    function ev_bind(num) {
        var lister = AMap.event.addListener(markers[num], 'click', function(ev) {
            if (this.getExtData()) {
                md.set('pedia_id', this.getExtData());
            }

            infowindow.setContent(ev.target.content);
            infowindow.open(mapObj, this.getPosition());

            log(ev.target.content)
            log(md.get('pedia_id'))

            marker = this;
        });
        listers.push(lister);
    };

    this.del = function(marker, callback) {
        var id = marker.getExtData();
        mconsole('id', id);
        /**
         * id的存在用以判断是否已进入过md编辑
         * @param  {[type]} id [description]
         * @return {[type]}    [description]
         */
        if (id) {
            $http({
                url: __API__._DelAtc_ + id,
                method: 'DELETE', //put更新,post添加
                data: '',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(data, status, headers, config) {
                console.log(data);
                mapObj.remove(marker);
                alert("删除成功");
            }).error(function(data, header, config, status) {
                console.log(data);
                console.log(header);
                console.log(status);
                alert(textStatus + "请检查网络连接");
            });
        } else {
            mapObj.remove(marker);
        }
        callback();
    };
    this.remove = function(marker, callback) {
        marker.setDraggable(true);
        callback();
    };
    this.get_all = function(callback) {
        $http({
            url: __API__._GetPediaFAll_,
            method: "GET",
            data: '',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function(data, status, headers, config) {
            var markers_msg = data.pedia;
            console.log(markers_msg);
            //渲染marker
            render(markers_msg, callback);

        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert(textStatus + "请检查网络连接")
        });
    };
    //进入编辑
    this.init_marker_lister = function() {
        for (var i = 0; i < markers.length; i++) {
            //事件绑定
            ev_bind(i)
        }
    };

    this.del_marker_lister = function() {
        for (var i = 0; i < listers.length; i++) {
            //移除监听
            AMap.event.removeListener(listers[i]);
        }
    };
    //正向地址编码
    this.addressCode = function(address) {
        var key = "f04042dbf08df4d6b9dd84837d6aa8f4";
        var url = "http://restapi.amap.com/v3/geocode/geo?address=" + address + "&output=JSON&key=" + key;
        var pos = 'asd';
        $http({
                url: url,
                method: "GET",
                data: '',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            })
            /**
             * position需要传入数组对象
             */
            .success(function(data, status, headers, config) {
                console.log(data.geocodes[0].location)
                var lnglat = data.geocodes[0].location;
                var position = lnglat;
                var zoomlevel = 10;
                lnglat = lnglat.split(',');

                if (isEdit) {
                    lock_btn('edit_add_f');
                }

                console.log(data.geocodes[0].level);
                /**
                 * 设置放大级别以及中心点
                 */
                mapObj.setZoomAndCenter(zoomlevel, lnglat);
                /**
                 * 填充入逆地址编码
                 */
                reAddressCode(position);

            }).error(function(data, header, config, status) {
                console.log(data);
                console.log(header);
                console.log(status);
                alert(textStatus + "请检查网络连接")
            });
    };
    //逆向地址编码
    this.reAddressCode = function(lnglat) {
        var key = "f04042dbf08df4d6b9dd84837d6aa8f4";
        var url = "http://restapi.amap.com/v3/geocode/regeo?output=json&location=" + lnglat + "&key=" + key + "&radius=1000&extensions=all";

        $http({
            url: url,
            method: "GET",
            data: '',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).success(function(data, status, headers, config) {
            console.log(data)
            console.log(data.regeocode.formatted_address)
            var address = data.regeocode.formatted_address;
            /**
             * 将信息填入md表单
             * @type {[type]}
             */
            md.set('province', data.regeocode.addressComponent.province);
            md.set('city', data.regeocode.addressComponent.city);
            md.set('location', lnglat);
            console.log(md.get_form())

            if (address != "")
                $$('readdress').value = address;
            else $$('readdress').value = "所查坐标超出能力范围";

        }).error(function(data, header, config, status) {
            console.log(data);
            console.log(header);
            console.log(status);
            alert(textStatus + "请检查网络连接")
        });
    }

    this.render_addresss = function() {}
    this.render_readdress = function() {}

    var reAddressCode = this.reAddressCode;
    var addressCode = this.addressCode;

    function render(markers_msg, callback) {
        for (var i = 0; i < markers_msg.length; i++) {
            //坐标结构化
            var lnglat = markers_msg[i].location.replace(/\(|\)/g, '').split(',');
            //init 标记
            var marker = new AMap.Marker({
                position: lnglat,
                zIndex: 101,
                title: markers_msg[i].title,
                topWhenMouseOver: true,
                // draggable: true,
                raiseOnDrag: true, //拖拽效果
                clickable: true,
                map: mapObj,
                extData: markers_msg[i].pedia_id
            });
            //加载icon
            if (markers_msg[i].pushpin) {
                var icon = new AMap.Icon({
                    image: markers_msg[i].pushpin,
                    size: new AMap.Size(38, 52),
                    //控制图标大小
                    imageSize: new AMap.Size(38, 52)
                        //icon缩放
                });
                //仅当icon为图片时才修正偏移
                var offset = new AMap.Pixel(-20, -50); //icon偏移量
                marker.setIcon(icon);
                marker.setOffset(offset);
            }

            marker.content = '<div class="ta-c"><a href=' + __API__._DOMAIN_ + 'science/recomm/' + markers_msg[i].pedia_id + ' class="btn bg-blue">去了解详情</a></div>';

            console.log(markers_msg[i]);
            markers.push(marker);

            // markers[i].content = markers_msg[i].pedia_id;
        };
        callback();
    };

};


/**
 * 专门维护一个预设数据对象
 */
function EditForm() {
    this.init = function(oj) {
        if (oj === Object(oj)) {
            this.form = oj;
        } else false;
    }
    this.get = function(key) {
        if (this.form[key] != undefined) {
            return this.form[key];
        } else {
            return false;
        }
    };
    this.set = function(key, value) {
        if (this.form[key] != undefined) {
            this.form[key] = value;
            return this.form[key];
        } else {
            return false;
        }
    };
    this.set_form = function(oj) {
        for (var key in oj) {
            // console.log(this.form[key])
            if (this.form[key] != undefined) {
                this.form[key] = oj[key];
            }
        }
        return this.form;
    };
    this.get_form = function() {
        return this.form;
    };
    this.render_input = function(id, content) {
        var input = document.getElementById(id);
        if (content) {
            input.value = content;
        }
    };
    this.render_elem = function(id, content) {
        var elem = document.getElementById(id);
        if (content) {
            elem.innerHTML = content;
        }
    };
    this.render_img = function(id, img_url) {
        if (img_url) {
            var container = document.getElementById(id);
            var img = document.createElement('img');
            img.src = img_url;
            if (!container.hasChildNodes()) {
                container.appendChild(img);
            } else {
                container.replaceChild(img, container.firstChild);
            }
        }
    };
}

function Article($http, $stateParams, $state, loading, md) {
    this.publish = function() {
        loading.show();
        if (document.forms[0].checkValidity()) {
            //在http中嵌套$stateParams会出现bad request
            var pedia_id = $stateParams.pedia_id;
            var context = '<link href="http://106.75.137.2:8888/static/css/default.css" rel="stylesheet">' + $$('preview').innerHTML;
            //init_md
            md.set_form({
                pedia_id: pedia_id,
                title: $$('md_category').value,
                city: $stateParams.city,
                province: $stateParams.province,
                category: $$('md_category').value,
                context: context,
                location: '(' + $stateParams.location + ')',
                markdown: $$('text-input').value
            });
            try {
                md.set('pushpin', $$('icon_box').firstElementChild.src);
            } catch (err) {
                console.log(err)
            }
            console.log(md.get_form())

            $http({
                url: __API__._AddPediaF_,
                method: pedia_id ? 'PUT' : 'POST', //put更新,post添加
                data: md.get_form(),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(data, status, headers, config) {
                console.log(data);
                /**
                 * 进入更新/新增逻辑状态->refash
                 * @type {[type]}
                 */
                $state.go('app_mager__gar_recom', {
                    provinces: $stateParams.province,
                    city: $stateParams.city,
                    location: $stateParams.location,
                    pedia_id: data.pedia_id | $stateParams.pedia_id
                });
                alert('发布 / 更新 成功！')
                loading.hide();
            }).error(function(data, header, config, status) {
                console.log(data);
                console.log(header);
                console.log(status);
                alert('请检查网络连接')
            });
        }
    };
    this.get = function(pedia_id) {
        loading.show();
        if (pedia_id) {
            $http({
                url: __API__._GetAtc_ + pedia_id,
                method: "GET",
                data: '',
                // params: {},
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).success(function(data, status, headers, config) {
                //update_msg
                md.set_form(data);
                // console.log(md.get_form());
                // console.log(data.pedia.location);

                //渲染必要信息
                // md.render_input('md_category', md.get('category'));
                // md.render_input('text-input', md.get('markdown'));
                // md.render_img('icon_box', md.get('pushpin'));
                // md.render_img('cover_box', md.get('coverurl'));
                md.render_elem('preview', md.get('context'));

                loading.hide();
            }).error(function(data, header, config, status) {
                console.log(data);
                console.log(header);
                console.log(status);
                alert('请检查网络连接')
            });
        } else return (function() {
            loading.hide();
        })();
    };
}

/**
 * 等待加载时的过度效果
 * @param {[type]} node [description]
 */
function Loading(node) {
    this.toggle = function() {
        if (node.classList.contains('d-n')) {
            node.classList.remove('d-n');
            node.classList.add('d-b');
        } else {
            node.classList.remove('d-b');
            node.classList.add('d-n');
        }
    };
    this.show = function() {
        if (node.classList.contains('d-n')) {
            node.classList.remove('d-n');
            node.classList.add('d-b');
        } else return false;
    };
    this.hide = function() {
        if (node.classList.contains('d-b')) {
            node.classList.remove('d-b');
            node.classList.add('d-n');
        } else return false;
    };
}
